import { AfterViewInit, Component, OnInit, Injector, Input, Output, EventEmitter, Inject, forwardRef } from '@angular/core';
import { MyTabPanel } from '../../../public/tabview/tabview.component';
import { IDisposable } from 'xterm';
import { BaseTermTabComponent } from '../../base-term-tab/base-term-tab.component';


@Component({
  selector: 'app-single-term',
  templateUrl: './single-term.component.html',
  styleUrls: ['./single-term.component.css']
})
export class SingleTermComponent extends BaseTermTabComponent implements OnInit, AfterViewInit {
  constructor(@Inject(forwardRef(() => MyTabPanel)) tabPanel: MyTabPanel, protected injector: Injector) {
    super(tabPanel, injector);
  }
  @Input() showClose: boolean;
  keyEvent: IDisposable;
  newTermSession() {
    if (this.session) this.xterm.write("\r\n");
    this.newSession(
      (path) => {
        this.resizeHandler();
        if (this.keyEvent) this.keyEvent.dispose();
      },
      (data) => {
        this.recvNewData = true;
        this.xterm.write(data);
      },
      (error) => {
        this.recvNewData = false;
        this.xterm.write("\r\n\r\n");
        this.xterm.writeln("\x1b[1;1;31mError:" + error + "\x1b[0m");
        this.xterm.writeln("Press CTRL + ENTER to reconnect!!");
        if (this.keyEvent) this.keyEvent.dispose();
        this.keyEvent = this.xterm.onKey((key) => {
          if (key.domEvent.ctrlKey && key.domEvent.key == 'Enter') {
            this.newTermSession();
            //this.xterm.clear();
            this.xterm.write("\r\n");
          }
        });
      }
    );
  }
  ngOnInit(): void { }
  ngAfterViewInit(): void {
    super.ngAfterViewInit();
    this.xterm.onData((input) => {
      if (this.session && this.session.writable) this.session.write(input);
    });
    this.xterm.onSelectionChange(() => {
      const text = this.xterm.getSelection();
      if (this.setting.terminal.rightCopy && text && text != "") {
        if (this.electron.isElectron) {
          this.electron.remote.clipboard.write({ text: text })
        } else {
          navigator.clipboard.writeText(text);
        }
      }
    })
    this.newTermSession();
  }
  async onRightClicked(event: MouseEvent) {
    event.stopPropagation();
    event.preventDefault();
    let text = '';
    if (this.setting.terminal.rightCopy) {
      if (this.electron.isElectron) {
        text = this.electron.remote.clipboard.readText();
      } else {
        text = await navigator.clipboard.readText();
      }
      this.session.write(text);
      this.xterm.scrollToBottom();
    }
  }
  @Output() onClose = new EventEmitter<any>();
  closeClicked() {
    this.onClose.emit();
  }
}
